//
//  File.swift
//  WebSocket
//
//  Created by yaqiang bi on 2017/5/3.
//
//

import Foundation
import PerfectLib
import PerfectHTTP
import PerfectWebSockets

/// 文件操作
func rocumentFile(){
    let thisFile = File("/Users/mac/Desktop/PerfectTemplate/Sources/1.docx")
    print("路径是否存在\(thisFile.exists)")
    print("文件路径\(thisFile.path)")
    print("绝对路径：\(thisFile.realPath)")
    do{
        try thisFile.open(.readWrite)
        
    }catch{
        fatalError("\(error)")
    }
    
    do{
       let write = try thisFile.write(string: "你好！！！")
        print("写入成功\(write)")
    }catch{
        fatalError("\(error)")
    }
    
    do{
        let contents = try thisFile.readString()
        print("读取成功\(contents)")
    }catch{
        fatalError("\(error)")
    }
    
    do{
        let bytesWritten = try thisFile.write(bytes: [90,21], dataPosition: 0, length: 2)
        print(bytesWritten)
    }catch{
        fatalError("\(error)")
    }
    
    thisFile.close()
    //thisFile.delete()
    print("文件大小:\(thisFile.size)")
    print("是否为一个符号链接\(thisFile.isLink)")
    print("当前文件是否为一个目录:\(thisFile.isDir)")
    print("文件的UNIX权限信息\(thisFile.perms.rawValue)")
//    do{
//        let file = try thisFile.moveTo(path: "/Users/yaqiangbi/Desktop/WebSocket/")
//        print(file.path)
//    }catch{
//        fatalError("\(error)")
//    }
    
    do{
        try thisFile.lock(byteCount: 0)
        let reslut = try thisFile.testLock(byteCount: 0)
        print("文件是否锁定\(reslut)")
    }catch{
        fatalError("\(error)")
    }
    
    do{
        try thisFile.unlock(byteCount: 0)
    }catch{
        fatalError("\(error)")
    }
    
    
    let createFile = File("/Users/mac/Desktop/PerfectTemplate/Sources/2.txt")
    do{
        try createFile.open(.readWrite)
    }catch{
        fatalError("\(error)")
    }
    
    do{
        try createFile.write(string: "你好")
    }catch{
        fatalError("\(error)")
    }
    
    do{
        let content = try createFile.readString()
        print("2.txt的内容\(content)")
    }catch{
        fatalError("\(error)")
    }
    createFile.close()
    
    let thisDir = Dir("/Users/mac/Desktop/PerfectTemplate/Sources/document/")
    do{
        try thisDir.create(perms: .rwxUser)
    }catch{
        print("文件创建失败")
    }
    
}

/// 目录和路径
func dir(){
    let thisDir = Dir("/Users/mac/Desktop/PerfectTemplate/Sources/document")
    print("目录是否存在\(thisDir.exists)")
    print("当前目录的名称\(thisDir.name)")
    let workingDir = Dir.workingDir
    print("当前目录的工作路径\(workingDir.path)")
    
    let createFile = File("\(thisDir.path)3.txt")
    do{
        try createFile.open(.readWrite)
    }catch{
        print("3.txt文件创建失败")
    }
    
    do{
        try createFile.write(string: "你好，我们是中国人民解放军")
    }catch{
        print("3.txt写入失败")
    }
    
    do{
        try thisDir.forEachEntry(closure: { (path) in
            print(path)
        })
    }catch{
        print("目录树读取失败 ")
    }
}
